<template>
  <div class="park-detail">
    <div class="park-list">
      <span>{{ berthData.address }}</span>
      <span>历史订单</span>
    </div>
    <div class="park-content">
      <div class="park-detail-head">
        <span>泊车号：{{ berthData.code }}</span>
        <van-icon name="cross" @click="close" />
      </div>
      <div class="park-detail-body">
        <div class="park-detail-title">车辆信息</div>
        <div class="park-detail-car">
          <span>车牌号码：</span>
          <span>{{ berthData.carNumber || "暂无" }}</span>
        </div>
        <div class="park-detail-car">
          <span>车辆类型：</span>
          <span>{{ berthData.plateType_dictText || "暂无" }}</span>
        </div>
        <div class="park-detail-car">
          <span>进场时间：</span>
          <span>{{ berthData.startTime || "暂无" }}</span>
        </div>
        <div class="park-detail-car">
          <span>当前费用：</span>
          <span>{{ berthData.currentCash || "暂无" }}</span>
        </div>
        <div class="park-detail-car">
          <span>停车时间：</span>
          <span>{{ berthData.parkingDurationStr || "暂无" }}</span>
        </div>

        <div class="park-detail-title">设备信息</div>
        <div class="park-detail-car">
          <span>设备号码：</span>
          <span>{{ berthData.deviceCode || "暂无" }}</span>
        </div>
        <div class="park-detail-car">
          <span>设备类型：</span>
          <span>{{ berthData.lbType || "暂无" }}</span>
        </div>
        <div class="park-detail-car">
          <span>设备信号：</span>
          <span>{{ berthData.lbLink || "暂无" }}</span>
        </div>
        <div class="park-detail-car">
          <span>设备卡号：</span>
          <span>{{ berthData.lbNumber || "暂无" }}</span>
        </div>
        <div class="park-detail-car">
          <span>运营商：</span>
          <span>{{ berthData.lbCompany || "暂无" }}</span>
        </div>
      </div>
      <div class="park-detail-foot">
        <van-button
          type="primary"
          border
          :color="berthData.status == '0' ? '#226bf4' : '#504e4e'"
          hairline
          :disabled="berthData.status == '1'"
          @click="createOrder"
          >创建订单</van-button
        >
        <van-button
          type="primary"
          border
          :color="berthData.status == '1' ? '#226bf4' : '#504e4e'"
          hairline
          :disabled="berthData.status == '0'"
          @click="urgeCall"
          >催缴欠费</van-button
        >
        <van-button
          type="primary"
          border
          :color="berthData.status == '1' ? '#226bf4' : '#504e4e'"
          hairline
          :disabled="berthData.status == '0'"
          @click="doubleUrge"
          >双倍收费</van-button
        >
        <van-button
          type="primary"
          border
          :color="berthData.status == '1' ? '#226bf4' : '#504e4e'"
          hairline
          :disabled="berthData.status == '0'"
          @click="printReceipt"
          >打印小票</van-button
        >
        <van-button
          type="primary"
          border
          :color="berthData.status == '1' ? '#226bf4' : '#504e4e'"
          hairline
          disabled
          @click="changeCar"
          >修改车牌</van-button
        >
        <van-button
          type="primary"
          border
          :color="berthData.status == '1' ? '#226bf4' : '#504e4e'"
          hairline
          :disabled="berthData.status == '0'"
          @click="endOrder"
          >结束订单</van-button
        >
      </div>
    </div>
    <van-dialog
      v-model="showModifyPlateDialog"
      title="修改车牌"
      show-cancel-button
      @confirm="confirmModifyPlate"
    >
      <div style="padding: 20px;">
        <van-field
          v-model="newCarNumber"
          placeholder="请输入新车牌号码"
          clearable
        />
      </div>
    </van-dialog>

    <van-dialog
      v-model="showSettlementDialog"
      title="手动结算"
      show-cancel-button
      @confirm="confirmManualSettlement"
    >
      <div style="padding: 20px;">
        <van-field
          v-model="settlementData.discountAmount"
          type="number"
          label="优惠金额"
          placeholder="请输入优惠金额（整数）"
        />
        <van-field
          v-model="settlementData.handleDesc"
          label="说明"
          placeholder="请输入结算说明"
        />
      </div>
    </van-dialog>
  </div>
</template>
<script>
export default {
  props: {
    berthData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      show: false,
      showModifyPlateDialog: false,
      newCarNumber: "",
      currentBerthData: {},
      showSettlementDialog: false,
      settlementData: {
        parkingId: null,
        vehicleIndex: null,
        discountAmount: 0,
        handleDesc: ""
      }
    };
  },
  methods: {
    close() {
      this.$emit("close");
    },
    createOrder() {
      this.$router.push({
        path: "/work/createOrder",
        query: this.berthData
      });
    },
    urgeCall() {},
    doubleUrge() {
      this.$dialog
        .confirm({
          title: "双倍收费确认",
          message: "确定要执行双倍收费吗？",
          confirmButtonColor: "#ee0a24"
        })
        .then(async () => {
          try {
            if (!this.berthData.orderId) {
              this.$toast.fail(" 缺失订单ID");
              return;
            }
            const { code, message } = await this.baseService.get(
              "/parking/bizParkingOrder/doubleFee?id=" + this.berthData.orderId
            );
            if (code === 200) {
              this.$toast.success(" 双倍收费成功");
            } else {
              this.$toast.fail(message || "操作失败");
            }
          } catch (error) {
            console.error(" 双倍收费异常:", error);
            this.$toast.fail(" 网络请求异常");
          } finally {
          }
        });
    },
    printReceipt() {
      console.log("触发了方法--打印小票-->");
    },
    async changeCar() {
      this.showModifyPlateDialog = true;
    },
    // 更新泊位信息 -修改车牌
    async confirmModifyPlate() {
      try {
        this.berthData.carNumber = this.newCarNumber;
        const { code, message } = await this.baseService.post(
          "//parking/parkingCarPort/edit",
          this.berthData
        );
        if (code === 200) {
          this.$toast.success("修改成功");
        } else {
          this.$toast.fail(message || "修改失败");
        }
      } catch (error) {
        console.error("修改车牌异常:", error);
        this.$toast.fail("请求失败");
      }
    },
    endOrder() {
      this.showSettlementDialog = true;
    },
    // 确认手动结算
    async confirmManualSettlement() {
      try {
        const { parkingId } = this.berthData;
        const discountAmount = this.settlementData.discountAmount;
        const handleDesc = this.settlementData.handleDesc;
        if (this.berthData.tradeNo) {
          // 生成结束时间（ISO格式转指定格式）
          const formatTime = date => {
            const pad = n => n.toString().padStart(2, "0");
            return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
              date.getDate()
            )} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
              date.getSeconds()
            )}`;
          };
          // 计算实际缴费金额（总费用 - 优惠金额）
          const settlementFee = Math.max(
            0,
            (this.berthData.fee_orig || 0) - (parseInt(discountAmount) || 0)
          );
          const params = {
            discountAmount: parseInt(discountAmount) || 0,
            handleDesc: handleDesc,
            endTime: formatTime(new Date()),
            totalFee: this.berthData.fee_orig,
            parkingDuration: this.berthData.parkingDuration_ori, // 添加停车时长
            settlementFee: settlementFee, // 添加实际缴费
            tradeNo: this.berthData.tradeNo
            // tradeNo: "01202411290000003"
          };

          const { code, message } = await this.baseService.post(
            `/parking/bizParkingOrder/manualSettlement`,
            params
          );
          if (code === 200) {
            this.$toast.success("结算成功");
          } else {
            this.$toast.fail(message || "结算失败");
          }
        } else {
          const { code, message } = await this.baseService.get(
            `/parking/bizParkingOrder/endOrder?id=${this.berthData.orderId}`
          );

          if (code === 200) {
            this.$toast.success(" 订单已结束");
          } else {
            this.$toast.fail(message || "结束订单失败");
          }
        }
      } catch (error) {
        console.error("手动结算异常:", error);
        this.$toast.fail("请求失败");
      } finally {
        this.showSettlementDialog = false;
        this.settlementData = {
          parkingId: null,
          vehicleIndex: null,
          discountAmount: 0,
          handleDesc: ""
        };
      }
    }
  }
};
</script>
<style lang="less" scoped>
.park-detail {
  height: 100%;
  padding: 10px;
  .park-list {
    background-color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    padding: 0px 20px;
    span:nth-child(1) {
      font-size: 20px;
      font-weight: bold;
    }
    span:nth-child(2) {
      font-size: 12px;
      color: blue;
    }
  }
  .park-content {
    background-color: #dbeafe;
    //   height: 95%;
  }
  .park-detail-head {
    width: 100%;
    border-bottom: 1px solid #ccc;
    height: 50px;
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    span {
      line-height: 40px;
      font-weight: bold;
    }
  }
  .park-detail-title {
    font-weight: bold;
    font-size: 16px;
    margin-top: 10px;
  }
  .park-detail-body {
    padding: 10px;
  }
  .park-detail-car {
    span {
      margin-right: 10px;
      color: #666;
      font-size: 14px;
    }
  }
  .park-detail-foot {
    margin-top: 10px;
    display: flex;
    justify-content: space-evenly;
    flex-wrap: wrap;
    height: 100px;
  }
}
</style>
